package com.linjj.seckill.service.impl;

import com.linjj.seckill.domain.Order;
import com.linjj.seckill.domain.SeckillOrder;
import com.linjj.seckill.domain.User;
import com.linjj.seckill.mapper.OrderMapper;
import com.linjj.seckill.redis.RedisService;
import com.linjj.seckill.redis.SeckillOrderKey;
import com.linjj.seckill.service.IOrderService;
import com.linjj.seckill.vo.OrderDetailVo;
import com.linjj.seckill.vo.SeckillGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderService implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    RedisService redisService;

    @Override
    public List<OrderDetailVo> getUserOrders(User user) {
        return orderMapper.queryOrderDetailVoByUserId(user.getUserId());
    }

    /**
     * 根据订单号查询订单详情
     * */
    @Override
    public OrderDetailVo getOrderDetailVoByOrderId(long orderId) {
        return orderMapper.queryOrderDetailVoByOrderId(orderId);
    }

    /**
     * 创建订单
     * */
    @Override
    @Transactional
    public Order createOrder(User user, SeckillGoodsVo seckillVo,String address) {
        Order order = new Order(user.getUserId(),seckillVo.getId(),address,seckillVo.getGoodsName(),1,seckillVo.getSeckillPrice(),0,0,new Date());
        orderMapper.insertOrder(order);
        SeckillOrder seckillOrder = new SeckillOrder(user.getUserId(),order.getId(),seckillVo.getId());
        orderMapper.insertSeckillOrder(seckillOrder);
        redisService.set(SeckillOrderKey.getSeckillOrderByUserIdAndGoodsId,user.getUserId()+"_"+seckillVo.getId(),seckillOrder);
        return order;
    }
    /**
     *查询是否重复秒杀
     *先从redis中查询，找不到再到数据库中查询
     *防止大量用户重复点击导致数据库压力过大
     * */
    @Override
    public SeckillOrder getSeckillOrderByUserIdAndGoodsId(long userId,long goodsId){
        SeckillOrder seckillOrder;
        seckillOrder = redisService.get(SeckillOrderKey.getSeckillOrderByUserIdAndGoodsId,userId+"_"+goodsId,SeckillOrder.class);
        if(seckillOrder==null){
            seckillOrder = orderMapper.querySeckillOrderByUserIdAndGoodsId(userId,goodsId);
            if(seckillOrder!=null){
                redisService.set(SeckillOrderKey.getSeckillOrderByUserIdAndGoodsId,userId+"_"+goodsId,seckillOrder);
            }
        }
        return seckillOrder;
    }
}
